package com.power.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.power.constant.Constant;
import com.power.model.TUser;
import org.springframework.security.core.context.SecurityContextHolder;

import java.nio.charset.StandardCharsets;

public class LoginInfoUtil {
    /**
     * 获取登录的用户信息
     *
     * @return
     */
    public static TUser getCurrentLoginUser() {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        TUser tUser = (TUser) authentication.getPrincipal();
        return (TUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    /**
     * 从token中解析初TUser
     *
     * @param token
     * @return
     */
    public static TUser getUserFromToken(String token) {
        boolean verifyToken = false;
        try {
            verifyToken = JWTUtil.verify(token, Constant.LOGIN_JWT_SECRET.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            //token验证异常
            throw new RuntimeException("token验证异常");
        }
        if (!verifyToken) {
            throw new RuntimeException("token验证失败");
        }
        JSONObject payloads = JWTUtil.parseToken(token).getPayloads();
        String userJSON = payloads.get("user", String.class);
        TUser tUser = JSONUtil.toBean(userJSON, TUser.class);
        return tUser;
    }
}
